/**
 Copyright (C) 2013 Yuyao Liang

 This source code is release under the BSD License.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.

 Created on Oct 14, 2013 2:07:11 PM
 */
package com.googlecode.stereoplot;

import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;

import javax.swing.event.EventListenerList;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.util.ParamChecks;

/**
 * @author lianyuy
 * 
 */
public class StereoPlotChartPanel extends ChartPanel {

	private static final long serialVersionUID = -1811577459168858148L;
	private transient EventListenerList MouseDragListeners;
	private boolean pressed = false;

	/**
	 * @param chart
	 */
	public StereoPlotChartPanel(JFreeChart chart) {
		super(chart);
		this.MouseDragListeners = new EventListenerList();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jfree.chart.ChartPanel#mouseDragged(java.awt.event.MouseEvent)
	 */
	@Override
	public void mouseDragged(MouseEvent e) {
		super.mouseDragged(e);

		Object[] listeners = this.MouseDragListeners
				.getListeners(ChartMouseDragListener.class);
		if (listeners.length == 0) {
			return;
		}

		Insets insets = getInsets();
		int x = (int) ((e.getX() - insets.left) / this.getScaleX());
		int y = (int) ((e.getY() - insets.top) / this.getScaleY());

		this.setAnchor(new Point2D.Double(x, y));
		if (this.getChart() == null) {
			return;
		}
		this.getChart().setNotify(true); // force a redraw

		ChartEntity entity = null;
		if (this.getChartRenderingInfo() != null) {
			EntityCollection entities = this.getChartRenderingInfo()
					.getEntityCollection();
			if (entities != null) {
				entity = entities.getEntity(x, y);
			}
		}

		if (this.getChart() != null) {
			ChartMouseDragEvent event = new ChartMouseDragEvent(getChart(), e,
					entity);
			for (int i = listeners.length - 1; i >= 0; i -= 1) {
				((ChartMouseDragListener) listeners[i])
						.chartMouseDragged(event);
			}

			if (pressed)
				mouseClicked(e);
		}

	}

	public void addChartMouseDragListener(ChartMouseDragListener listener) {
		ParamChecks.nullNotPermitted(listener, "listener");
		this.MouseDragListeners.add(ChartMouseDragListener.class, listener);
	}

	public void removeChartMouseDragListener(ChartMouseDragListener listener) {
		this.MouseDragListeners.remove(ChartMouseDragListener.class, listener);
	}

	@Override
	public void mousePressed(MouseEvent e) {
		super.mousePressed(e);
		pressed = true;
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		super.mouseReleased(e);
		pressed = false;
	}

}
